<script setup>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  onMounted,
  ref,
  nextTick,
  watch,
} from "vue";
import { useStore } from "vuex";

import ColorPicker from "colorpicker-v3";
import "colorpicker-v3/style.css";
import {
  QuestionCircleOutlined,
  UploadOutlined,
  CloudUploadOutlined,
  CaretRightOutlined,
  CloseOutlined,
} from "@ant-design/icons-vue";

// import { sticker_urls_item } from '@/views/shotstack/MixedCutPlatforms/utools/template.js'

import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";

// sticker 手机组件
import stickerPhone from './components/stickerPhone.vue'
const stickerPhoneRef = ref()
import { message } from "ant-design-vue";
// 封装的请求
import request from "@/common/utils/request";

import {isEmpty} from '@/common/utils/is.js'

const props = defineProps({
  targetIndex: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits('updateSticker:confige')

  const state = reactive({
    visible: false, //控制页面显示隐藏
    addVisible: false, //控制素材库组件显示隐藏
    // 手机组件 显示隐藏
      phoneVisible: false,
      // 贴纸来源 tabs
      activeKey:'1',
      marks:{
      0: {
          style: {
              color: '#333',
          fontSize:'12px'
          },
          label: '透明',
      },
      1: {
          style: {
              color: '#333',
              fontSize:'12px'
          },
          label: '不透明',
      },
    },

    // 贴纸列表
    stickerList:[]
  });

const formState = reactive({
  start_time: 0,
  duration:60,
  use_stickers: [
    // {
    //     "width": 511,
    //     "height": 512,
    //     "x": 0,
    //     "y": 0,
    //     "url": "https://vod.jukeyinqing.com/common/sticker/30d919616f8eaa267e49e91a24baa1f7.gif",
    //     "id": 806,
    //     "media_id": "149a4100d3f071ef80b5f6e7d4486301",
    //     "isUse": true
    // }
  ],
  stickersMaterial:[]
})

// 添加贴纸
const stickerAdd = (item, type) => {

  const maxNum = 50

  // 限制贴纸数量
  if (formState.use_stickers.length >= maxNum) {
    message.warning(`最多添加${maxNum}个贴纸`)
    return
  }

    // 固定的宽高大小
    const num = 100

    let newWidth = Number(item?.width)??0
    let newHeight = Number(item?.height)??0

    // 如果宽高都大于0 就按比例缩放
    if (newWidth > 0 && newHeight > 0) {
      const maximum = Math.max(newWidth, newHeight)
      const scale = num / maximum 
      newWidth = Math.round(newWidth * scale )
      newHeight = Math.round(newHeight * scale )
    }

  if (type == 'customize') {
    formState.use_stickers.push(JSON.parse(JSON.stringify({
      ...item,
      width: newWidth || item?.width,
      height: newHeight || item?.height,
    })))
  } else {
    const pushItem = {
        "x": 0,
        "y": 0,
        "url": item.material_url,
        "id": item.id,
        "media_id": item.media_id,
        width: newWidth || item?.width,
        height: newHeight || item?.height,
        material_extension: item?.material_extension ?? '',
        dync_frames: item?.dync_frames?? '',   

    }
    formState.use_stickers.push(JSON.parse(JSON.stringify(pushItem)))
  }

}

    // 仓库
    const store = useStore();

    // 选择文件组件回调
const cancel = (info) => {
  console.log(info, '选择的素材');
  if (isEmpty(info)) {
    state.addVisible = false;
    return
    }

    const pushArr = info.filter(ele => !formState.stickersMaterial.find(item => item?.id == ele?.id)).map(item => {
        return {
            width: item?.width,
            height: item?.height,
            x: 0,
            y:0,
            url: item?.material_url,
            id: item?.id,
            media_id: item?.oss_media_id ?? '',  
            material_extension: item?.material_extension ?? '',
            dync_frames: item?.dyncFrames?? '',   
        }
    })
    formState.stickersMaterial.push(...pushArr)
    state.addVisible = false;
};

// 更新某个贴纸数据
const updateItem = (params) =>{
  const { data, type } = params
  const { index, ...athers } = data
  console.log(index,'更新的下标???');

  Object.assign(formState.use_stickers?.[index], athers)
}

// 删除某个正在使用的贴纸
const delItem = (index) => {
  formState.use_stickers.splice(index, 1)
}
    
  // 删除某个贴纸素材
const clear = (index) => {
    formState.stickersMaterial.splice(index, 1)
};

  // 确定添加sticker
const submit = () => {
  emit('updateSticker', formState)
  onClose()
}

    // 打开弹窗
const showDrawer = (sticker_confige) => {
  console.log(sticker_confige, '当前视频组的配置??');
  for (let key in sticker_confige) {
    formState[key] = JSON.parse(JSON.stringify(sticker_confige[key]))
  }
  state.visible = true;
  state.phoneVisible = true

  nextTick(() => {
    stickerPhoneRef.value?.useBgc()
  });

  getStickerList()
};

// 获取 贴纸数据
const getStickerList = async () => {
  const res = await request.get(
        "work_ai",
        `/user/shotstack/stickers/list`
  )

  console.log(res,'贴纸数据');
  state.stickerList = res?.result??[]
  
}

    // 关闭弹窗
    const onClose = () => {
      state.visible = false;
    };
    defineExpose({
      showDrawer,
      onClose
    })

</script>

<template>
  <a-drawer v-model:visible="state.visible" class="custom-class" title="选择贴纸" placement="right" width="800"
    :maskClosable="false">

        <!-- 设置显示的时间 -->
         <!-- <div>
            <a-time-picker v-model:value="formState.time" valueFormat="mm:ss" format="mm:ss" />
         </div> -->
         <div class="sticker_configs">
          <div class="sticker_configs_item">
            <div class="sticker_configs_item_title">显示开始时间: </div>
            <div class="item_title_content">
              <a-input-number style="width: 130px;" :precision="4" v-model:value="formState.start_time" :min="0" :max="999999" />
              <div class="sticker_configs_item_title">单位/秒</div>
            </div>

          </div>
          <div class="sticker_configs_item">
            <div class="sticker_configs_item_title">显示持续时长: </div>
            <div class="item_title_content">
              <a-input-number style="width: 130px;" :precision="4" v-model:value="formState.duration" :min="0" :max="999999" />
              <div class="sticker_configs_item_title">单位/秒</div>
            </div>
          </div>
        </div>


        <a-tabs v-model:activeKey="state.activeKey">
            <a-tab-pane key="1" tab="自定义">
                <div class="colorList">
                  <div class="color-item-upload" @click="state.addVisible = true">
                    <div class="color-item-upload-add">
                      <span>+</span>
                      <!-- <upload-outlined /> -->
                      <span class="color-item-upload-top">素材库导入</span>
                    </div>
                    <!-- <div class="color-item-uploadOpreat">
                      <span class="color-item-upload-top" @click="state.addVisible = true"><upload-outlined />素材库导入</span>
                    </div> -->
                  </div>
                  <template v-if="formState.stickersMaterial.length">
                      <div class="color-item" v-for="(item,index) in formState.stickersMaterial" :key="item.id">
                        <img style="height: 100%;width: 100%;object-fit: contain" v-lazy="item?.url" alt="" />
                        <div class="close" @click="clear(index)">
                          <close-outlined />
                        </div>
                        <a-button 
                        @click="stickerAdd(item, 'customize')"
                        type="primary" size="small" class="use_button">
                           添加
                    </a-button>
                      </div>
                  </template>
                </div>
            </a-tab-pane>

            <a-tab-pane v-for="item in state.stickerList" :key="`${item?.id}_${item?.scene_type}`" :tab="item.name">
                <div class="colorList">
                  <div class="color-item" v-for="(ele,index) in item.materials" :key="ele.id">
                        <img style="height: 100%;width: 100%;object-fit: contain" v-lazy="ele?.material_url" alt="" />
                        <a-button 
                        @click="stickerAdd(ele, 'ather')"
                        type="primary" size="small" class="use_button">
                           添加
                    </a-button>
                      </div>
                </div>
            </a-tab-pane>
        </a-tabs>

          <!-- 手机组件 -->
        <stickerPhone ref="stickerPhoneRef" 
        :phoneVisible="state.phoneVisible"
        :visible="state.visible"
        :stickerData="formState.use_stickers"
        :targetIndex="props.targetIndex"
        @updateItem="updateItem"
        @delItem="delItem"
        > </stickerPhone>
        <!-- :formState.stickersMaterial="formState.use_stickers" -->
    <template #footer>
      <a-row type="flex" justify="end">
        <a-button style="margin-right: 8px" type="primary" @click="submit">确认添加</a-button>
        <a-button @click="onClose">取消</a-button>
      </a-row>
    </template>
    <!-- 素材库导入 -->
    <ChooseMaterial :haveTags="[
      {
        name: '网络素材',
        key: 'system_materials',
      }
    ]" useType="视频背景" 
    :isClip="false" material_type="image" 
    :visible="state.addVisible" @close="cancel" 
    :multiple="true" />
  </a-drawer>
</template>

<style lang="less" scoped>
.cube {
  width: 30px;
  height: 30px;
  border-radius: 5px;
  position: relative;
}

.colorList {
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 12px;
  max-height: 600px;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 8px;
    /* 滚动条的宽度 */
    height: 10px;
    /* 滚动条的高度，垂直滚动条可能用得上 */
    display: none;
  }

  &::-webkit-scrollbar-thumb {
    background: #888;
    /* 滑块的背景颜色 */
    border-radius: 10px;
    /* 滑块的圆角 */

  }
}

.color-item,
.color-item-upload {
  cursor: pointer;
  height: 140px;
  margin-top: 10px;
  background: #f7f7f7;
  border: 1px solid #e6e6e7;
  border-radius: 5px;

  .check_btn {
    position: absolute;
    top: 0;
    left: 0;
  }
}

.color-item-upload {
  background: #f7f7f7;

  .color-item-upload-add {
    width: 100%;
    font-size: 30px;
    display: flex;
    height: 100%;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    
    .color-item-upload-top{
        font-size: 14px;
    }
  }

  .color-item-uploadOpreat {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    height: 100%;
    // visibility: hidden;
    cursor: pointer;

    .color-item-upload-top,
    .color-item-upload-bottom {
      display: flex;
      height: 49%;
      align-items: center;
      justify-content: center;
    }

    .color-item-upload-top:hover,
    .color-item-upload-bottom:hover {
      color: #2878ff;
    }

    .color-item-upload-middle {
      height: 1px;
      width: 80%;
      background: #e6e6e7;
    }
  }
}



.color-item {
  position: relative;

  .use_button{
    position: absolute;
    bottom: 5px;
    right: 5px;
    border-radius: 100px; 
    overflow: hidden;
    font-size: 12px;
    padding: 0 10px;
  }
}

.close {
  width: 20px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  position: absolute;
  right: 0;
  top: 0;
  font-size: 10px;
  border-radius: 10px;
  border: 1px solid #c1c1c1;
  background: #fff;
  visibility: hidden;
}

.color-item:hover .close {
  visibility: visible;
}

.colorPicker {
  background: skyblue;
}


// 表单box
.sticker_configs{
  display: flex;
  margin-top: 20px;

  gap: 20px;

  .sticker_configs_item{
    display: flex;
    
    // flex-direction: column;
    align-items: center;
    gap: 10px;
    gap: 10px;
    .item_title_content{
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 10px;
    }

  .sticker_configs_item_title{
    font-size: 14px;
    color: #333;
    margin-bottom: 3px;
    font-weight: bold;
  

    .question{

    }
  }
  .input_content{
    flex: 1;
  }

  }

}

</style>
